package com.binlan.util;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class ExcelUtil {
	
	 //delete update drop -- create truncate  exec xp_cmdshell

    public void exportListMap(String title, List<String> heads, List<Map<String, Object>> list, OutputStream outputStream) {
        boolean flag = false;
        HSSFWorkbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet(title);
        CellStyle style = workbook.createCellStyle();
        int rowIndex = 0;
        Row row = sheet.createRow(rowIndex);
        for (int i = 0; i < heads.size(); i++) {
            Cell cell = row.createCell(i);
            sheet.setColumnWidth(i, 5000);
            style.setAlignment(CellStyle.ALIGN_CENTER);
            cell.setCellValue(heads.get(i));
        }

        for (int i = 0; i < list.size(); i++) {
            rowIndex++;
            row = sheet.createRow(rowIndex);
            Map<String, Object> rowObj = list.get(i);
            for (int j = 0; j < heads.size(); j++) {
                Cell cell = row.createCell(j);
                sheet.setColumnWidth(j, 5000);
                style.setAlignment(CellStyle.ALIGN_CENTER);
                cell.setCellValue(Objects.toString(rowObj.get(heads.get(j)), ""));
            }
        }

        try {
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
//        List<Map<String, Object>> list = new ArrayList<>();
//        Map<String, Object> map1 = new HashMap<>();
//        map1.put("tx1", "xv1");
//        map1.put("tx2", "xv5");
//        list.add(map1);
//        list.add(map1);
//        list.add(map1);
//        FileOutputStream outputStream = new FileOutputStream(new File("G:\\11.xls"));
//        ExcelUtil excelUtil = new ExcelUtil();
//        excelUtil.exportListMap("excel测试标题", Arrays.asList(new String[]{"tx1", "tx2"}), list, outputStream);

//        System.out.printf(String.valueOf(null));
    }
}
